﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using TPOJ.Model;
using TPOJ.BLL;
using System.Web.Caching;
using TPOJ.CacheDependencyFactory;

namespace TPOJ.Web
{
    public class AccountDataProxy
    {
        private static readonly int accountTimeout = int.Parse(ConfigurationManager.AppSettings["AccountCacheDuration"]);
        private static readonly bool enableCaching = bool.Parse(ConfigurationManager.AppSettings["EnableCaching"]);

        public static Account GetAccount(int id)
        {
            AccountBO accountBO = new AccountBO();

            if (!enableCaching)
                return accountBO.GetAccount(id);

            string key = "account" + id;
            Account data = (Account)HttpRuntime.Cache[key];

            if (data == null)
            {
                data = accountBO.GetAccount(id);

                AggregateCacheDependency aggrCacheDependency = DependencyFacade.getAccountDependency();

                HttpRuntime.Cache.Add(key, data, aggrCacheDependency, DateTime.Now.AddHours(accountTimeout), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
            }
            return data;
        }

        public static int GetAccountRank(int userId)
        {
            AccountBO accountBO = new AccountBO();

            return accountBO.GetAccountRank(userId);
        }

        public static IList<Tuple<int,Account>> GetNeighboursByUserId(int userId, out int rank)
        {
            AccountBO accountBO = new AccountBO();
            rank = 0;

            if (!enableCaching)
                return accountBO.GetNeighboursByUserId(userId, out rank);

            string key = "neighbours_user" + userId;

            var data = (IList<Tuple <int,Account>>)HttpRuntime.Cache[key];

            if (data == null)
            {
                data = accountBO.GetNeighboursByUserId(userId, out rank);

                AggregateCacheDependency aggrCacheDependency = DependencyFacade.GetProblemDependency();

                HttpRuntime.Cache.Add(key, data, aggrCacheDependency, DateTime.Now.AddHours(accountTimeout), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
            }
            return data;
        }
    }
}